#include "RPGChatMainWindow.h"
#include "WhiteboardTab.h"
#include "ui_rpgchat.h"
#include "Macros.h"
#include <QtGui>

RPGChat::RPGChat(QWidget *parent) :
    QMainWindow(parent), _ui(new Ui::RPGChat), _shiftPressed(false)
{
    _ui->setupUi(this);
    setupSignalsSlots();
}

RPGChat::~RPGChat()
{
    SAFE_DELETE(_ui);
}

void RPGChat::setupSignalsSlots(void)
{
    // menu items
    connect(_ui->actionFoobar, SIGNAL(triggered()), this, SLOT(foobarTest()));
	connect(_ui->actionRemoveFoobar, SIGNAL(triggered()), this, SLOT(removeFoobarTest()));

	connect(_ui->actionOpenWhiteboardTab, SIGNAL(triggered()), this, SLOT(openWhiteboardTab()));

    connect(_ui->actionAbout, SIGNAL(triggered()), this, SLOT(about()));
    connect(_ui->actionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

    // button items
    connect(_ui->sendButton, SIGNAL(clicked()), this, SLOT(sendMessage()));
    connect(_ui->messageText, SIGNAL(textChanged()), this, SLOT(checkForEnter()));
}

void RPGChat::foobarTest(void)
{
    _ui->connectedUsers->addItem("Foo");
}

void RPGChat::removeFoobarTest(void)
{
	QList<QListWidgetItem*> entries = _ui->connectedUsers->findItems("Foo", Qt::MatchFixedString);

	if (!entries.empty()) {
		int row = _ui->connectedUsers->row(entries.front());
		_ui->connectedUsers->takeItem(row);
	}
}

void RPGChat::checkForEnter(void)
{
    QString message = _ui->messageText->toPlainText();
	if (message.endsWith('\n')) {
		if (!_shiftPressed) {
			if (message.size() > 1) {
				// remove the newline to avoid double-spacing
				message.remove(message.lastIndexOf('\n'), 1);
				_ui->messageText->setText(message);
				sendMessage();
			} else
				_ui->messageText->clear();
		}
	}
}

void RPGChat::sendMessage(void)
{
    QString message = _ui->messageText->toPlainText();
    _ui->messageText->clear();

    _ui->chatWindow->append(message);

    // network shit goes here
}

void RPGChat::openWhiteboardTab(void)
{
	Whiteboard* whiteboard = new Whiteboard;

	whiteboard->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(whiteboard, SIGNAL(customContextMenuRequested(const QPoint&)), whiteboard, SLOT(contextMenu(const QPoint&)));

	_ui->tabWidget->addTab(whiteboard, tr("Personal Whiteboard"));
}

void RPGChat::about(void)
{
    QMessageBox::about(this, tr("About RPGChat"),
            tr("<p><b>RPGChat</b> is a chat client designed to help people play pen and paper RPGs"
               " over the internet.</p>"));
}

void RPGChat::keyPressEvent(QKeyEvent* event)
{
	QMainWindow::keyPressEvent(event);

	if (event->key() == Qt::Key_Shift)
		_shiftPressed = true;
}

void RPGChat::keyReleaseEvent(QKeyEvent* event)
{
	QMainWindow::keyReleaseEvent(event);

	if (event->key() == Qt::Key_Shift)
		_shiftPressed = false;
}